﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.Entity;
using com.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule;
using BusinessRule.WareHouse;

public partial class Inventory_In : PageBase
{

    public decimal ID;
    private static WAREHOUSE_VOUCHER_HEADER header = null;
    private DataTable Products = null;

    private void InitTable()
    {
        Products = new DataTable();
        Products.Columns.Add(new DataColumn("ID"));
        Products.Columns.Add(new DataColumn("QUANTITY", typeof(Int32)));
        Products.Columns.Add(new DataColumn("ProductName"));
        Products.Columns.Add(new DataColumn("PRODUCTID",typeof(int)));
        Products.Columns.Add(new DataColumn("CODE"));
        Products.Columns.Add(new DataColumn("WAREHOUSE"));
        Products.Columns.Add(new DataColumn("PIECE_PRICE", typeof(float)));
        Products.Columns.Add(new DataColumn("LINE_AMOUNT", typeof(float)));
        Products.Columns.Add(new DataColumn("UOM", typeof(String)));
        Products.Columns.Add(new DataColumn("CONVERSIONFACTOR", typeof(UInt16)));
        ViewState["DATA"] = Products;
    }

    private void InitData()
    {
        header = new WarehouseVoucherManager().Load(ID, MyStateManager.DomainID, out Products);
        if (header != null)
        {
            txtAmount1.Text = header.PAYABLES.ToString();
            txtAmount2.Text = header.ACTUALPAID.ToString();
            txtCode.Text = header.VOUCHERCODE.ToString();
            txtCode.ReadOnly = true;
            txtDate.Text = BusinessLogic.GetDateTime(header.VOUCHERDATE.ToString(), "yyyyMMddHHmmss", "yyyy-MM-dd");
            txtDate.ReadOnly = true;
            txtDate.Attributes.Add("onfocus",null);
           
            ddlSupply.SelectedValue = header.SUPPLYID.ToString();
            ddlSupply.Enabled = false;
            txtRemark.Text = header.REMARK;

        }

        this.GridView.DataSource = Products;
        GridView.DataBind();
        ViewState["DATA"] = Products;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            InitTable();
            if (String.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                txtCode.Text = "CG-" + MyStateManager.UserID + "-" + DateTime.Now.ToString("yyyyMMddHHmmss");
                txtDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }
            else
            {
                ID = decimal.Parse(Request.QueryString["ID"]);
                InitData();
            }
            //绑定供货商
            ddlSupply.DataSource = new SupplyManager().Query(MyStateManager.DomainID, null, 1);
            ddlSupply.DataBind();
            //插入选择项
            AddSelectItemInFirst(ddlSupply);

           
        }
        else if("SelectProduct".Equals(Request.Form["__EVENTTARGET"]))
        {
            String PROIDUCTid = Request.Form["__EVENTARGUMENT"];
            //插入到已选择产品列表
            AddProduct(PROIDUCTid);
        }

    }

    protected void TextChanged(object sender, EventArgs e)
    {
        float totalamount=0;
        if (Products == null)
            Products = ViewState["DATA"] as DataTable;
        foreach (GridViewRow rowItem in GridView.Rows)
        {
            var rows = Products.Select("CODE='" + GridView.DataKeys[rowItem.DataItemIndex].Value.ToString() + "'");
            if (rows.Count() == 0)
                continue;
            DataRow datarow = rows[0];
            var WareHouse = rowItem.Cells[1].FindControl("ddlWareHouse") as DropDownList;
            if (WareHouse.SelectedIndex > 0)
                datarow["WAREHOUSE"] = WareHouse.SelectedValue;
            var UOM = rowItem.Cells[3].FindControl("ddlUOM") as DropDownList;
            if (UOM.SelectedIndex > 0)
            {
                datarow["UOM"] = UOM.SelectedIndex == 1 ? "PC" : "CS";
                datarow["CONVERSIONFACTOR"] = UOM.SelectedValue;
            }
            //保存数量
            var textbox = rowItem.Cells[4].FindControl("txtQuantity") as TextBox;
            int quantity = 0;
            bool changed = false;
            if (textbox != null && !String.IsNullOrEmpty(textbox.Text))
            {
                if (int.TryParse(textbox.Text, out quantity))
                {
                    datarow["QUANTITY"] = quantity;
                    if (sender == textbox)
                        changed = true;
                }
            }
            //保存采购价
            float pieceprice = 0;
            textbox = rowItem.Cells[5].FindControl("txtPiecePrice") as TextBox;
            if (textbox != null && !String.IsNullOrEmpty(textbox.Text))
            {
                if (float.TryParse(textbox.Text, out pieceprice))
                {
                    datarow["PIECE_PRICE"] = pieceprice;
                    if (sender == textbox)
                        changed = true;
                }
            }
            float amount = 0;
            //保存金额
            textbox = rowItem.Cells[6].FindControl("txtAmount") as TextBox;
            if (textbox != null && !String.IsNullOrEmpty(textbox.Text))
            {

                if (float.TryParse(textbox.Text, out amount))
                    datarow["LINE_AMOUNT"] = amount;

            }
            if (amount == 0 || changed)
            {
                 amount = quantity * pieceprice;
                 datarow["LINE_AMOUNT"] = amount;
                 textbox.Text = amount.ToString();
               
            }
            totalamount += amount;
        }
        txtAmount1.Text = totalamount.ToString();
        txtAmount2.Text = txtAmount1.Text;
    }

    private void AddProduct(String productID)
    {
        //查找该产品
        var product = new ProductManager().Load(int.Parse(productID));
        Products = ViewState["DATA"] as DataTable;
        if (product != null && product.ACTIVE)
        {
            var row = Products.NewRow();
            Products.Rows.Add(row);
            row["CODE"] = "MX-" + MyStateManager.UserID + "-" + DateTime.Now.ToString("yyyyMMddHHmmss");
            row["PRODUCTID"] = product.ID;
            row["ProductName"] = product.ProductName;
            row["PIECE_PRICE"] = product.PIECE_PRICE;
            row["LINE_AMOUNT"] = 0;
            row["QUANTITY"] = 0;
            //刷新之前选择的产品数据
            TextChanged(null, EventArgs.Empty);
           
            GridView.DataSource = Products;
            GridView.DataBind();
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!this.IsValid)
            return;
        //需要选择仓库
        if (ddlSupply.SelectedIndex == 0)
        {
            ShowMessage("请选择供货商,谢谢");
            return;
        }
        //判断是新增还是保存
        if(header == null)
            header = new WAREHOUSE_VOUCHER_HEADER();
        header.VOUCHERCODE = txtCode.Text;
        header.VOUCHERDATE = BusinessLogic.GetDateTimeDecimal(DateTime.Parse(txtDate.Text));
        header.REMARK = txtRemark.Text;
        header.SUPPLYID = decimal.Parse(ddlSupply.SelectedValue);
        header.PAYABLES = decimal.Parse(txtAmount1.Text);
        header.ACTUALPAID = decimal.Parse(txtAmount2.Text);
        header.DOMAINID = MyStateManager.DomainID;
        header.LASTUPDATER = MyStateManager.UserID.ToString();
        header.OPERATORID = MyStateManager.UserID;
        header.ACTIVE = true;
        System.Collections.Generic.List<WAREHOUSE_VOUCHER_LINE> lines = new System.Collections.Generic.List<WAREHOUSE_VOUCHER_LINE>();

        if (Products == null)
            Products = ViewState["DATA"] as DataTable;
        foreach (GridViewRow rowItem in GridView.Rows)
        {
            var rows = Products.Select("CODE='" + GridView.DataKeys[rowItem.DataItemIndex].Value.ToString() + "'");
            if (rows.Count() == 0)
                continue;
            DataRow datarow = rows[0];
            var WareHouse = rowItem.Cells[1].FindControl("ddlWareHouse") as DropDownList;
            if (WareHouse.SelectedIndex == 0)
            {
                ShowMessage("请选择商品" + rowItem.Cells[2].Text + "入库仓,谢谢");
                return;
            }
            datarow["WAREHOUSE"] = WareHouse.SelectedValue;
            var UOM = rowItem.Cells[3].FindControl("ddlUOM") as DropDownList;
            if (UOM.SelectedIndex == 0)
            {
                ShowMessage("请选择商品" + rowItem.Cells[2].Text + "计量单位,谢谢");
                return;
            }
            if (UOM.SelectedIndex > 0)
            {
                datarow["UOM"] = UOM.SelectedIndex == 1 ? "PC" : "CS";
                datarow["CONVERSIONFACTOR"] = UOM.SelectedValue;
            }

           
            //保存数量
            var textbox = rowItem.Cells[4].FindControl("txtQuantity") as TextBox;
            int quantity = 0;
            if (textbox != null && !String.IsNullOrEmpty(textbox.Text))
            {
                if (int.TryParse(textbox.Text, out quantity))
                    datarow["QUANTITY"] = quantity;
            }
            if (quantity <= 0)
            {
                ShowMessage("商品" + rowItem.Cells[2].Text + "的入库数量不能小于等于0，否则请从入库单中移除，谢谢！");
                return;
            }
            //保存采购价
            float pieceprice = 0;
            textbox = rowItem.Cells[5].FindControl("txtPiecePrice") as TextBox;
            if (textbox != null && !String.IsNullOrEmpty(textbox.Text))
            {
                if (float.TryParse(textbox.Text, out pieceprice))
                    datarow["PIECE_PRICE"] = pieceprice;
            }
            float amount = 0;
            //保存金额
            textbox = rowItem.Cells[6].FindControl("txtAmount") as TextBox;
            if (textbox != null && !String.IsNullOrEmpty(textbox.Text))
            {

                if (float.TryParse(textbox.Text, out amount))
                    datarow["LINE_AMOUNT"] = amount;

            }
            if (amount == 0)
            {
                amount = quantity * pieceprice;
                datarow["LINE_AMOUNT"] = amount;
                textbox.Text = amount.ToString();

            }
            if (datarow["ID"] != DBNull.Value)
                continue;
            var line = new WAREHOUSE_VOUCHER_LINE();
            line.VOUCHERLINECODE = rowItem.Cells[0].Text;
            line.UNIT = datarow["UOM"].ToString();
            line.CONVERSIONFACTOR = uint.Parse(datarow["CONVERSIONFACTOR"].ToString());
            line.QUANTITY = quantity;
            line.WAREID = decimal.Parse(datarow["WAREHOUSE"].ToString());
            line.PRODUCTID = decimal.Parse(datarow["PRODUCTID"].ToString());
            line.PIECEPRICE =  decimal.Parse(pieceprice.ToString());
            line.OPERATORID = MyStateManager.UserID;
            line.LINEAMOUNT = decimal.Parse(amount.ToString());
            lines.Add(line);
        }

        try
        {

            var success = new BusinessRule.WareHouse.WarehouseVoucherManager().Save(header, lines.ToArray());
            if (success)
            {
                ScriptManager.RegisterStartupScript(GridView, typeof(Page), "SUCCESS", "alert('入库单添加成功');location.href='INVENTORY_LIST.aspx';", true);
                //ShowMessage("入库单添加成功");
                //Response.Redirect("INVENTORY_LIST.aspx");
            }
            else
            {
                ShowMessage("入库单添加失败");
            }
        }
        catch (Exception err)
        {
            this.ShowMessage(err.Message);
        }
    }

    /// <summary>
    /// 绑定数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.DataRow)
            return;
        DataRowView view = e.Row.DataItem as DataRowView;
        
        var WareHouse = e.Row.Cells[1].FindControl("ddlWareHouse") as DropDownList;
        WareHouse.DataSource = WareHouseManager.GetWareHouse(MyStateManager.DomainID);
        WareHouse.DataBind();
        this.AddSelectItemInFirst(WareHouse);
       
        WareHouse.SelectedValue = view["WAREHOUSE"].ToString();
        //设置商品单位
        var UOM = e.Row.Cells[3].FindControl("ddlUOM") as DropDownList;
      
        var uom = Product_UomsManager.GetProductUom(MyStateManager.DomainID, (int)view["PRODUCTID"]);
        this.AddSelectItemInFirst(UOM);
        if (uom != null)
        {
            UOM.Items.Add(new ListItem() { Text = uom.PCNAME, Value = "1" });
            UOM.Items.Add(new ListItem() { Text = uom.CSNAME, Value = uom.DENOMINATOR.ToString() });
        }
        else
        {
            UOM.Items.Add(new ListItem() { Text = "默认单位", Value = "1"  });
        }
        UOM.SelectedValue = view["UOM"].ToString();
        var delete = e.Row.Cells[e.Row.Cells.Count-1].Controls[0] as Button;
        delete.Attributes.Add("onclick", "if(confirm('你确定要从入库单中删除该商品?'))");
        if (view["ID"] != DBNull.Value)
        {
            delete.Visible = false;
            WareHouse.Enabled = false;
            UOM.Enabled = false;
            (e.Row.Cells[4].FindControl("txtQuantity") as TextBox).ReadOnly= true;
            (e.Row.Cells[5].FindControl("txtPiecePrice") as TextBox).ReadOnly = true;
            (e.Row.Cells[6].FindControl("txtAmount") as TextBox).ReadOnly = true;
        }
    }

    ////选择了一个商品单位,显示该商品的价格
    //protected void UOM_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    var UOM = sender as DropDownList;
    //    string[] ids = UOM.ClientID.Split('_');
    //    int index = int.Parse(ids[ids.Length - 2].Replace("ctl",""))-2;
    //    //获取单位价格

    //    ShowMessage(index.ToString());
    //}


    protected void GridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Products = ViewState["DATA"] as DataTable;
        Products.Rows.RemoveAt(e.RowIndex);
        TextChanged(sender, EventArgs.Empty);
        GridView.DataSource = Products;
        GridView.DataBind();
    }
}
